<template>
  <div :id="props.name" :style="styleObject"></div>
</template>

<script setup lang="ts">
import type { EChartsOption } from "echarts";
import * as echarts from "echarts";
import { onBeforeUnmount, onMounted, reactive, watch } from "vue";

interface Props {
  option: EChartsOption;
  name: string;
}
const props = defineProps<Props>();
// 图表样式
const styleObject = reactive({
  width: "100%",
  height: "100%",
});
// 准备图表节点
let myChart: undefined | echarts.ECharts;

// 监听图表的配置，一旦变化则重新绘制图表
watch(
  () => props.option,
  (newValue) => {
    myChart?.setOption(newValue, true);
  },
  { deep: true, immediate: false }
);

// 图表自适应
function resizeChart() {
  myChart?.resize();
}

onMounted(() => {
  // 初始化图表
  myChart = echarts.init(document.getElementById(props.name));
  myChart.setOption(props.option);

  // 监听窗口变化，让图表自适应
  window.addEventListener("resize", resizeChart);
});

onBeforeUnmount(() => {
  // 销毁图表
  myChart?.dispose();

  // 移除事件
  window.removeEventListener("resize", resizeChart);
});
</script>
